package com.yangdage.aop;

import com.yangdage.service.TokenUtilService;
import com.yangdage.util.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class ServiceValidateTokenAspect {
    Logger log = LoggerFactory.getLogger(ServiceValidateTokenAspect.class);

    @Autowired
    private TokenUtilService tokenService;


    @Pointcut("@annotation(com.yangdage.annonations.ServiceTokenRequired)")
    public void validateToken(){}


    /**
     * 验证token
     * @param joinPoint
     * @return
     * @throws Throwable
     * @author: 杨大哥
     */
    @Around("validateToken()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
        Object result = null;
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            return "token为空";
        }
        String userInfo = "mydlq";
        // 根据 Token 和与用户相关的信息到 Redis 验证是否存在对应的信息
        boolean ret = tokenService.validToken(token, userInfo);
        if(ret==false){
            return "重复调用";
        }
        result = joinPoint.proceed();
        return result;
    }
}
